package com.zhangshitong.service;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zhangshitong.dao.SysDeptMapper;
import com.zhangshitong.exception.ParamException;
import com.zhangshitong.model.SysDept;
import com.zhangshitong.param.DeptParam;
import com.zhangshitong.util.BeanValidator;
import com.zhangshitong.util.LevelUtilCopy;

@Service
public class DeptServiceCopy {

	@Resource
	SysDeptMapper sysDeptMapper;
	
	public void save(DeptParam param){
		BeanValidator.check(param);//先检查前端传递过来的参数是否符合要求
		if(check(param.getName(),param.getParentId(),param.getId())){
			throw new ParamException("新增的部门已经存在");
		}
		SysDept dept=SysDept.builder().name(param.getName()).id(param.getId()).parentId(param.getParentId())
				.seq(param.getSeq()).remark(param.getRemark()).build();
		dept.setLevel(LevelUtilCopy.calculateLevel(getParentLevel(param.getParentId()), param.getParentId()));
		dept.setOperateIp("127.0.0.1");
		dept.setOperator("admin");
		dept.setOperateTime(new Date());
		sysDeptMapper.insert(dept);
		
	}
	
	//更新比新增会麻烦一些,因为更新还要更新子部门的level  涉及到部门树,其实主要是level，parentId和seq排序等在前台已经更改
	public void update(DeptParam param){
		BeanValidator.check(param);
		if(check(param.getName(),param.getParentId(),param.getId())){
			throw new ParamException("更新的部门已经存在");
		}
		SysDept before = sysDeptMapper.selectByPrimaryKey(param.getId());
		SysDept after =SysDept.builder().name(param.getName()).parentId(param.getParentId()).id(param.getId())
				.seq(param.getSeq()).remark(param.getRemark()).build();
		after.setOperateIp("127.0.0.1");
		after.setOperator("updateDept");
		after.setOperateTime(new Date());
		
		updateWithChild(before,after);
		
	}
	
	public void updateWithChild(SysDept before,SysDept after){
		
	}
	public String getParentLevel(Integer parentId){
		SysDept dept =sysDeptMapper.selectByPrimaryKey(parentId);
		if(dept == null){
			return null;
		}
		return dept.getLevel();
	}
	public boolean check(String deptName,Integer parentId,Integer id){
		return false;
	}
}
